<?php
namespace App\Libraries\classs;
use App\Models\Sms;
use Carbon\Carbon;
use HavenShen\YunpianSMS\Facades\YunpianSMS;
class SmsLib{
    public static function sendSms($phone,$x_uid){
        $code = mt_rand(100000,999999);
        $nowtime =$startime = time();
        $endtime = $startime+600;
        $sms_data =array(
            'phone'=>$phone,
            'code'=>$code,
            'startime'=>$startime,
            'endtime'=>$endtime,
        );
        $where =array('phone'=>$phone);  //查询条件
        if($x_uid) {
            $where['x_uid'] = $x_uid;
            $sms_data['x_uid'] = $x_uid;
        }
        $count = Sms::where($where)->where('startime','>',$nowtime-600)->orderBy('id','desc')->count();
        if($count <3) {
            $sms = Sms::where($where)->orderBy('id', 'desc')->first();
            if ($sms) {
                if ($sms->startime + 60 > $nowtime) {
                    return array('success' => false, 'msg' => "请60秒钟后重发");
                }
                $sms_data['status'] = 1;
            } else {
                $sms_data['status'] = 1;
            }
            $sendCode = YunpianSMS::sendSMS($phone,$code);
//            $sendCode = "{\"code\":0,\"msg\":\"OK\",\"result\":{\"count\":1,\"fee\":0.055,\"sid\":11354262712}}";
            $sendCode = object2array(getJson($sendCode));
            if ($sendCode['code'] === 0) {
                Sms::create($sms_data)->save();
                return array('success' => true, 'msg' => '发送短信成功!');
            }
            return array('success' => false, 'msg' => $sendCode);
        }
        return array('success'=>false,'msg'=>'发送太频繁了,请稍后发送!');
    }

    public static function VerifyCode($phone,$code,$x_uid = null){
      if($phone || $code){
          $time = time();
          $where =array('phone'=>$phone,'code'=>$code,'status'=>1);
          if($x_uid){
             $where['x_uid']=$x_uid;
          }
          $sms = Sms::where($where)->where('startime','<',$time)->where('endtime','>',$time)->orderBy('id','desc')->first();
          if($sms){
                $sms->status=2;
                $sms->update();
              return array('success'=>true,'msg'=>'短信验证成功!');
          }
          return array('success'=>false,'msg'=>'验证码失效,请获取短信验证码!');
      }
      return array('success'=>false,'msg'=>'手机号码或验证为空');
    }
}